package com.wltt.product.ahuthr.component;

import com.wltt.product.ahuthr.enums.RemindTypeEnum;
import com.wltt.product.ahuthr.mapper.*;
import com.wltt.product.ahuthr.model.bo.AgreementBO;
import com.wltt.product.ahuthr.model.po.AgreementAttachFilePO;
import com.wltt.product.ahuthr.model.po.AgreementPO;
import com.wltt.product.ahuthr.model.po.AttachFilePO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class AgreementComponent {

    @Resource
    private AgreementMapper agreementMapper;

    @Resource
    private AgreementAttributeMapper agreementAttributeMapper;

    @Resource
    private AgreementAttachFileMapper agreementAttachFileMapper;

    @Resource
    private AttachFileMapper attachFileMapper;

    @Resource
    private RemindMapper remindMapper;

    /**
     * 根据合同id删除
     *
     * @param agreementId
     * @return
     */
    public void deleteAgreementById(Long agreementId) {

        // 删除属性
        agreementAttributeMapper.deleteByAgreementId(agreementId);

        // 删除附件
        List<AttachFilePO> attachFilePOList = new ArrayList<>();
        List<AgreementAttachFilePO> agreementAttachFilePOList = agreementAttachFileMapper.queryByAgreementId(agreementId);
        if (!CollectionUtils.isEmpty(agreementAttachFilePOList)) {
            agreementAttachFileMapper.deleteByAgreementId(agreementId);
            attachFilePOList = attachFileMapper.queryByIds(agreementAttachFilePOList.stream().map(AgreementAttachFilePO::getAttachFileId).collect(Collectors.toList()));
            attachFileMapper.deleteByIds(attachFilePOList.stream().map(AttachFilePO::getId).collect(Collectors.toList()));
        }

        // 删除合同主表
        agreementMapper.deleteById(agreementId);

        // 删除提醒表
        remindMapper.deleteByRemindTypeAndObz(RemindTypeEnum.AGREEMENT_TYPE.getCode(), String.valueOf(agreementId));

    }

    /**
     * 根据人员id删除
     *
     * @param userId
     * @return
     */
    public void deleteAgreementByUserId(Long userId) {
        List<AgreementBO> agreementBOList = agreementMapper.queryByUserId(userId);
        if (CollectionUtils.isEmpty(agreementBOList)) {
            return;
        }
        for (AgreementBO agreementBO : agreementBOList) {
            deleteAgreementById(agreementBO.getId());
        }
    }
}
